import 'dart:async';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:fate_blind_box/im/video_model.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../network/Api.dart';
import '../theme/theme_color.dart';
import '../utils/provider.dart';
import '../utils/voice_animation_image.dart';
import '../widget/icon_text.dart';


class WebChatPage extends StatefulWidget {
  final String easeuserId;

  const WebChatPage(this.easeuserId, {Key? key}) : super(key: key);

  @override
  State<WebChatPage> createState() => _WebChatPageState();
}

class _WebChatPageState extends State<WebChatPage> {
  VideoModel videoModel = VideoModel();
  final GlobalKey _formKey = GlobalKey<FormState>();
  final TextEditingController _messController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  bool canSend = false;
  late String centext;
  late String membersex = "";
  final List<String> _logText = [];
  Map<String, dynamic> map = {};
  final List<Map> _items = [];
  final ScrollController scrollController = ScrollController();

  late double _screenWidth, _screenHeight;
  List<dynamic> lists = [];

  Map _userInfo = {};
  late Timer _timer;

  final int _maxLength = 600;
  int num = 0;
  String voiceIco = "images/voice_volume_7.png";
  String _path = "";
  final List<String> _assetList = [
    "images/voice_volume_1.png",
    "images/voice_volume_2.png",
    "images/voice_volume_3.png",
    "images/voice_volume_4.png",
    "images/voice_volume_5.png",
    "images/voice_volume_6.png",
    "images/voice_volume_7.png",
  ];

  bool isStop = true;

  var isshouw = false;

  var mesLis = 0;

  void validateInput(String test) {
    setState(() {
      canSend = test.isNotEmpty;
      centext = test;
    });
  }

  showView() {
    showDialog(
        context: context,
        builder: (context) {
          return Center(
              child: SizedBox(
                  child: Stack(alignment: Alignment.topCenter, children: [
            Container(
                // decoration: BoxDecorationUtil().setFillBoxDecoration(Colors.white, 14.0),
                margin: const EdgeInsets.only(top: 35, right: 52, left: 52),
                child: Column(mainAxisSize: MainAxisSize.min, children: [
                  Row(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        VoiceAnimationImage(
                          _assetList,
                          100,
                          100,
                          isStop,
                        ),
                      ]),
                ]))
          ])));
        });
    setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (kDebugMode) {
      //  print('rx--环信id--1111-----' + widget.easeuserId);
    }
    _getUserinfo();
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      // Brightness.light 状态栏字体颜色（白色）
      statusBarIconBrightness: Brightness.dark, // 状态栏字体颜色（黑色）
      statusBarColor: Color(0xff8F76F1), // 状态栏背景色
    ));

    if (lists.isNotEmpty) {
      setState(() {
        scrollController
            .jumpTo(scrollController.position.maxScrollExtent + 500);
      });
    }
  }

  void sendMess() {
    // 保证在组件build的第一帧时才去触发取消清空内容
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _messController.clear();
    });

    lists.add({
      "type": 1,
      "centext": centext,
    });
    _timer = Timer(const Duration(milliseconds: 1000), () {
      lists.add({
        "type": 2,
        "centext": "images/ic_download_app.png",
      });
      scrollController.jumpTo(scrollController.position.maxScrollExtent + 50);
      setState(() {});
    });
    scrollController.jumpTo(scrollController.position.maxScrollExtent + 50);
    setState(() {});
  }

  // 获取环信用户信息
  _getUserinfo() async {
    if (widget.easeuserId.isEmpty) return;
    final res = await Api.getInstance().getUserInfo(widget.easeuserId);
    final data = res['data'];
    if (data != null) {
      setState(() {
        _userInfo = data;
        if (_userInfo['realSex'] == 0) {
          membersex = '保密';
        }
        if (_userInfo['realSex'] == 1) {
          membersex = '男';
        }
        if (_userInfo['realSex'] == 2) {
          membersex = '女';
        }
      });
    } else {
      if (kDebugMode) {
        print('------获取用户异常---------------' + res['msg']);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        leading: BackButton(
          onPressed: () {
            if (_focusNode.hasFocus) {
              _focusNode.unfocus();
              _timer = Timer(const Duration(milliseconds: 400), () {
                Navigator.of(context).pop();
              });
            } else {
              Navigator.of(context).pop();
            }
          },
        ),
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Color(0xff5640A7),
                Color(0xff35267F),
              ],
            ),
          ),
        ),
        centerTitle: true,
        title: const Text(""),
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            colors: [
              Color(0xff5640A7),
              Color(0xff35267F),
            ],
          ),
        ),
        child: Column(
          children: <Widget>[
            Container(
              margin: const EdgeInsets.fromLTRB(19, 0, 0, 20),
              child: Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(3),
                    child: Image.network(
                      Provider.fixAvatar(_userInfo['profilePhoto']),
                      width: 60,
                      height: 60,
                      fit: BoxFit.fill,
                    ),
                  ),
                  const SizedBox(
                    width: 12,
                  ),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        margin: const EdgeInsets.only(right: 9),
                        child: Text(
                          _userInfo['nickName'] ?? "",
                          style: TextStyle(
                              color: ThemeColor.shadowColor,
                              fontSize: 16,
                              fontWeight: FontWeight.normal),
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Container(
                            padding: const EdgeInsets.only(
                                left: 5, right: 5, top: 2, bottom: 2),
                            decoration: BoxDecoration(
                              color: _userInfo['realSex'] == 2
                                  ? ThemeColor.mainColor
                                  : ThemeColor.nanColor,
                              borderRadius:
                                  const BorderRadius.all(Radius.circular(69.0)),
                            ),
                            child: IconText(
                              _userInfo['age'].toString() == 'null'
                                  ? ' 0'
                                  : ' ${_userInfo['age'].toString()}',
                              icon: Icon(
                                  _userInfo['realSex'] == 2
                                      ? Icons.female
                                      : Icons.male,
                                  color: Colors.white),
                              iconSize: 10,
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 10,
                              ),
                            ),
                          ),
                          Container(
                            margin: const EdgeInsets.only(left: 6),
                            padding: const EdgeInsets.only(
                                left: 6, right: 6, top: 2, bottom: 2),
                            // decoration: const BoxDecoration(
                            //   color:Color(0xffA28FEE),
                            //   borderRadius: BorderRadius.all(Radius.circular(2.0)),
                            // ),
                            child: Text(
                              "北京·汉族",
                              style: TextStyle(
                                  color: ThemeColor.shadowColor,
                                  fontSize: 12,
                                  fontWeight: FontWeight.normal),
                            ),
                          ),
                          Container(
                            margin: const EdgeInsets.only(left: 9),
                            padding: const EdgeInsets.only(
                                left: 11, right: 11, top: 3, bottom: 3),
                            decoration: const BoxDecoration(
                              color: Color(0xff6B54C5),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(69.0)),
                            ),
                            child: Text(
                              _userInfo['isRealAuth'] == 0 ? "已实名" : "未实名",
                              style: TextStyle(
                                  color: ThemeColor.shadowColor,
                                  fontSize: 10,
                                  fontWeight: FontWeight.normal),
                            ),
                          ),
                        ],
                      ),
                      Container(
                        // width: 200,
                        margin: const EdgeInsets.only(top: 7),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                InkWell(
                                  onTap: () {
                                    //更多信息
                                    // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => MemberDetail(),));
                                  },
                                  child: Container(
                                    padding: const EdgeInsets.only(
                                        left: 11, right: 11, top: 3, bottom: 3),
                                    decoration: const BoxDecoration(
                                      color: Color(0xffA28FEE),
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(2.0)),
                                    ),
                                    child: Text(
                                      "信息",
                                      style: TextStyle(
                                          color: ThemeColor.shadowColor,
                                          fontSize: 8,
                                          fontWeight: FontWeight.normal),
                                    ),
                                  ),
                                ),
                                InkWell(
                                  onTap: () {
                                    // if(_userInfo['id'].toString().isNotEmpty){
                                    //   Navigator.of(context).push(MaterialPageRoute(builder: (builder) => UserIntroduce(_userInfo['id'])));
                                    // }
                                  },
                                  child: Container(
                                    margin: const EdgeInsets.only(left: 14),
                                    padding: const EdgeInsets.only(
                                        left: 11, right: 11, top: 3, bottom: 3),
                                    decoration: const BoxDecoration(
                                      color: Color(0xffA28FEE),
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(2.0)),
                                    ),
                                    child: Text(
                                      "简介",
                                      style: TextStyle(
                                          color: ThemeColor.shadowColor,
                                          fontSize: 8,
                                          fontWeight: FontWeight.normal),
                                    ),
                                  ),
                                ),
                                Container(
                                  margin: const EdgeInsets.only(left: 14),
                                  padding: const EdgeInsets.only(
                                      left: 11, right: 11, top: 3, bottom: 3),
                                  decoration: const BoxDecoration(
                                    color: Color(0xffA28FEE),
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(2.0)),
                                  ),
                                  child: Text(
                                    "圈子",
                                    style: TextStyle(
                                        color: ThemeColor.shadowColor,
                                        fontSize: 8,
                                        fontWeight: FontWeight.normal),
                                  ),
                                ),
                              ],
                            ),
                            // Container(
                            //   margin: const EdgeInsets.only(left: 50),
                            //   padding: const EdgeInsets.only(
                            //       left: 8, right: 8, top: 3, bottom: 3),
                            //   decoration: BoxDecoration(
                            //     color: ThemeColor.shadowColor,
                            //     borderRadius: const BorderRadius.all(
                            //         Radius.circular(2.0)),
                            //   ),
                            //   child: Text(
                            //     "+备注",
                            //     style: TextStyle(
                            //         color: ThemeColor.sendimTextColor,
                            //         fontSize: 12,
                            //         fontWeight: FontWeight.normal),
                            //   ),
                            // ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Flexible(
              child: Container(
                margin: const EdgeInsets.only(left: 10, right: 10),
                decoration: BoxDecoration(
                  //背景
                  color: const Color(0xffF1F3FB),
                  //设置四周圆角 角度
                  borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(15.0),
                      topRight: Radius.circular(15.0)),
                  //设置四周边框
                  border: Border.all(width: 1, color: Colors.white),
                ),
                padding: const EdgeInsets.only(
                    left: 14, right: 14, top: 21, bottom: 21),
                child: ListView.builder(
                  controller: scrollController,
                  itemBuilder: (_, index) {
                    if (lists?.isNotEmpty == true) {
                      return Column(
                        children: <Widget>[
                          Row(
                            textDirection: lists[index]['type'] == 1
                                ? TextDirection.rtl
                                : TextDirection.ltr,
                            children: <Widget>[
                              Container(
                                  margin: const EdgeInsets.all(5),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(3),
                                    child: lists[index]['type'] == 1
                                        ? Image(
                                            image: CachedNetworkImageProvider(
                                                Provider.fixAvatar(
                                                    Provider.memberInfo[
                                                        'profilePhoto'])),
                                            height: 40,
                                            width: 40,
                                            fit: BoxFit.fill)
                                        : Image(
                                            image: CachedNetworkImageProvider(
                                                Provider.fixAvatar(
                                                    _userInfo['profilePhoto'])),
                                            height: 40,
                                            width: 40,
                                            fit: BoxFit.fill),
                                  )),
                              Container(
                                padding: const EdgeInsets.all(10),
                                constraints:
                                    const BoxConstraints(maxWidth: 240),
                                decoration: BoxDecoration(
                                    color: lists[index]['type'] == 1
                                        ? const Color(0xffffffff)
                                        : const Color(0xff98e165),
                                    borderRadius: BorderRadius.circular(3.0)),
                                child: lists[index]['centext']
                                        .toString()
                                        .contains('png')
                                    ? Image.asset(
                                        lists[index]['centext'],
                                        width: 100,
                                        height: 100,
                                      )
                                    : Text(
                                        lists[index]['centext'],
                                        style: const TextStyle(
                                          color: Colors.black,
                                          fontSize: 14,
                                        ),
                                      ),
                              ),
                            ],
                          )
                        ],
                      );
                    } else {
                      return Container();
                    }
                  },
                  itemCount: lists?.length,
                ),
              ),
            ),

            //ChatBottom(widget.easeuserId,scrollController),
            Container(
              height: 65,
              alignment: Alignment.center,
              margin: const EdgeInsets.only(left: 10, right: 10, bottom: 13),
              decoration: BoxDecoration(
                //背景
                color: Colors.white,
                //设置四周圆角 角度
                borderRadius: const BorderRadius.only(
                    bottomLeft: Radius.circular(15.0),
                    bottomRight: Radius.circular(15.0)),
                //设置四周边框
                border: Border.all(width: 1, color: Colors.white),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  const SizedBox(
                    width: 15,
                  ),
                  InkWell(
                    onTap: () {
                      //做弹起动画

                      if (isshouw) {
                        isshouw = false;
                        FocusScope.of(context).requestFocus(_focusNode); // 获取焦点
                      } else {
                        isshouw = true;
                        _focusNode.unfocus();
                      }
                    },
                    child: Container(
                      width: 24,
                      height: 24,
                      margin: const EdgeInsets.only(right: 5),
                      child: Image.asset(
                        'images/ic_volume.png',
                        width: 24,
                        height: 24,
                      ),
                    ),
                  ),
                  Offstage(
                    offstage: isshouw,
                    child: SizedBox(
                      child: Form(
                          key: _formKey,
                          child: SizedBox(
                            width: 200,
                            height: 40,
                            child: TextFormField(
                                autofocus: false,
                                maxLines: 3,
                                controller: _messController,
                                focusNode: _focusNode,
                                onChanged: validateInput,
                                keyboardType: TextInputType.text,
                                decoration: InputDecoration(
                                  isCollapsed: true,
                                  fillColor: const Color(0xffF1F3FB),
                                  filled: true,
                                  contentPadding: const EdgeInsets.symmetric(
                                      horizontal: 15, vertical: 10),
                                  enabledBorder: const OutlineInputBorder(
                                    /*边角*/
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(30), //边角为30
                                    ),
                                    borderSide: BorderSide(
                                      color: Colors.white54, //边线颜色为黄色
                                      width: 1, //边线宽度为2
                                    ),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(30),
                                      borderSide: const BorderSide(
                                        color: Colors.white54, //边框颜色为绿色
                                        width: 1, //宽度为5
                                      )),
                                )),
                          )),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(left: 5),
                    child: Image.asset(
                      'images/ic_emojis.png',
                      width: 24,
                      height: 24,
                    ),
                  ),
                  !canSend
                      ? Container(
                          margin: const EdgeInsets.only(left: 5),
                          child: Image.asset(
                            'images/ic_adds.png',
                            width: 24,
                            height: 24,
                          ),
                        )
                      : Container(),
                  Offstage(
                    offstage: !canSend,
                    child: InkWell(
                      onTap: () {
                        sendMess();
                      },
                      child: Container(
                        margin: const EdgeInsets.only(left: 5),
                        padding: const EdgeInsets.only(
                            left: 10, right: 10, top: 8, bottom: 8),
                        decoration: const BoxDecoration(
                          color: Colors.green,
                          borderRadius: BorderRadius.all(Radius.circular(3)),
                        ),
                        child: Text(
                          "确定",
                          style: TextStyle(
                              color: ThemeColor.shadowColor,
                              fontSize: 14,
                              fontWeight: FontWeight.normal),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
